import { Component, Input, ChangeDetectorRef } from "@angular/core";
import { SliderLevelModel } from "../../../../../../../shared/components/slider/sliderLevel.model";
import { BaseCriteriaTemplateComponent } from "../baseType.component";
import { ReportingService } from "../../../../../reporting.service";
import { Subscription } from "rxjs";
import * as _ from 'lodash';
import { ICriteriaTemplate, TemplateType } from "../../models/criteriaTemplate.interface";
import { ICriteriaOutput } from "../../models/save/criteriaOutput.interface";
import { SliderOutput } from "../../models/save/criteriaOutput.model";

@Component({
    selector: 'type5',
    templateUrl: 'type5.component.html',
    styleUrls: ['../../templateCriteria.component.scss'],
    providers: [{ provide: BaseCriteriaTemplateComponent, useExisting: Type5Component }]
})
export class Type5Component extends BaseCriteriaTemplateComponent implements ICriteriaTemplate {
    private sub: Subscription;
    public selectedDesc: string;
    public selectedId: number;
    public levels: SliderLevelModel[];

    public type: TemplateType = TemplateType.Slider;

    @Input() set answerCategories(value: any[]) {
        this.levels = [];

        let groupedCategories = _(value).groupBy('score').map((items, key) => {
            return { key: key, items: items };
        }).value();
        
        _.sortBy(groupedCategories, item => { return parseInt(item.key); }).forEach((item, index) => {
            this.levels.push(new SliderLevelModel(                
                item.key == '-1' ? 0 : parseInt(item.key) + 1,
                item.key == -1 ? item.items[0].text : item.key,
                item.key == -1 ? 'No Minimum threshold selected' : 'Minimum threshold is set to: ' + item.items.map(function (o) { return o.text.toLowerCase(); }).join(' or ')));
        });
    }

    constructor(
        private toolsService: ReportingService,
        private cdRef: ChangeDetectorRef) {
        super(toolsService, cdRef);
    }

    ngOnInit() {
        this.loadScoreData('typeFiveIsScreenableCriteriaItems')
        this.sub = this.load.subscribe(data => {
            this.selected = data || 0;
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }

    public set selected(value: number) {
        if (value !== undefined) {
            this.selectedId = value + 1;
            this.selectedDesc = this.levels.find(x => x.id == this.selectedId).desc;
        }
    }

    public sliderChanged(model) {
        this.selectedId = model.id;
        this.selectedDesc = model.desc;
        BaseCriteriaTemplateComponent.changed.emit(model.id != 0);
    }

    public save(): ICriteriaOutput {
        let model: SliderOutput = new SliderOutput(this.selectedId - 1, undefined);
        model.setBaseClass(this.templateCriteria);
        return model;
    }
}